package com.seal.commons.query.jdbctemplate;

import com.seal.commons.exception.RecordManyToOneException;
import com.seal.commons.query.DefaultQueryAdapter;
import com.seal.commons.query.DefaultQueryResult;
import com.seal.commons.query.QueryRequest;
import com.seal.commons.query.QueryResult;
import com.seal.commons.query.utils.FilterTextManipulator;
import com.seal.commons.query.utils.TextManipulator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.util.LinkedList;
import java.util.List;


/**
 * 功能描述: <br/>
 *
 * @author yong.huang
 * @date: 2020-06-24 14:11<br/>
 * @since JDK 1.8
 */
@Slf4j
public class JdbcQueryAdapter extends DefaultQueryAdapter {

    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private List<TextManipulator> manipulators;

    @Override
    public <T> QueryResult<T> query(String name, QueryRequest request, Class<T> clazz) {
        StringBuffer execuleSql =  new StringBuffer(getSql());
        for(TextManipulator textManipulator : getManipulators()){
           execuleSql = textManipulator.manipulate(new StringBuffer(execuleSql), request.getFilters());
        }
        if(isShowSql()){
            log.info("query sql:[{}]", execuleSql);
        }
        List<T> list = namedParameterJdbcTemplate.queryForList(execuleSql.toString(), request.getFilters(), clazz);
        if(request.getSingleQuery()){
            if(list != null && list.size() >1 ){
                throw new RecordManyToOneException("query one but found many more one");
            }
            return new DefaultQueryResult<>(list.get(0), request);
        }else{
            return new DefaultQueryResult<>(list, request);
        }
    }


   public List<TextManipulator> getManipulators(){
       if(manipulators == null){
           manipulators = new LinkedList<>();
           manipulators.add(new FilterTextManipulator());
       }
       return manipulators;
   }

    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
        return namedParameterJdbcTemplate;
    }


    public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    public void setManipulators(List<TextManipulator> manipulators) {
        this.manipulators = manipulators;
    }
}